import java.util.Arrays;

public class LeetCode977 {

    public static void main(String[] args) {
        int[] nums = {-4, -1, 0, 3, 10};

        Arrays.stream(sortedSquares(nums)).forEach(System.out::println);
    }

    public static int[] sortedSquares(int[] nums) {
        int n = nums.length;
        int[] res = new int[n];
        for (int i = 0, j = n - 1, pos = n - 1; i <= j; ) {
            if (nums[i] * nums[i] < nums[j] * nums[j]) {
                res[pos] = nums[j] * nums[j];
                j--;
            } else {
                res[pos] = nums[i] * nums[i];
                i++;
            }
            pos--;
        }
        return res;
    }
}
